package com.kedacom.freedomLabel.initdata;

import android.content.Context;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.kedacom.freedomLabel.AppExecutors;
import com.kedacom.freedomLabel.Options;
import com.kedacom.freedomLabel.initdata.bean.Classes;
import com.kedacom.freedomLabel.initdata.bean.ClassesBean;
import com.kedacom.freedomLabel.initdata.bean.ClonePostUtil;
import com.kedacom.freedomLabel.initdata.bean.EventBusMessage;
import com.kedacom.freedomLabel.initdata.bean.Goods;
import com.kedacom.freedomLabel.initdata.bean.GoodsBean;
import com.kedacom.freedomLabel.initdata.bean.Post;
import com.kedacom.freedomLabel.initdata.bean.PostMessage;
import com.kedacom.freedomLabel.initdata.bean.PostProduct;
import com.kedacom.freedomLabel.initdata.bean.PostRebackMess;
import com.kedacom.freedomLabel.initdata.bean.ProductDetail;
import com.kedacom.freedomLabel.initdata.bean.ProductDetailBean;
import com.kedacom.freedomLabel.initdata.bean.Staff;
import com.kedacom.freedomLabel.initdata.bean.StaffBean;
import com.kedacom.freedomLabel.initdata.bean.Team;
import com.kedacom.freedomLabel.initdata.bean.TeamBean;
import com.kedacom.freedomLabel.model.db.AppDatabase;
import com.kedacom.lego.message.LegoMessageManager;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.seray.scaleviewlib.utils.LogUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class InitAll {


    private static AppExecutors sExecutors;

    private static Gson gson = new GsonBuilder()
            .serializeNulls()
            .create();

    private static Handler sHandler = new Handler();

    public static String TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    static {
        sExecutors = AppExecutors.getInstance();
    }

    static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    public static void TestInterface01(String urlBase) {

        OkGo.<String>get(urlBase + "/Services/getGridModel")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            GoodsBean goodsBean = gson.fromJson(response.body(),
                                    new TypeToken<GoodsBean>() {
                                    }.getType());
                            if (goodsBean.getCode() == 200) {
                                LegoMessageManager.getInstance().sendMessage(Options.MSG_CONNECT_SUCCESS_TEST, new EventBusMessage(9, "服务器接口测试成功", "测试", 1));
                            }
                        } catch (Exception e) {
                            LegoMessageManager.getInstance().sendMessage(Options.MSG_CONNECT_SUCCESS_TEST, new EventBusMessage(9, "服务器测试接口返回异常", "测试", 0));
                        }


                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        LegoMessageManager.getInstance().sendMessage(Options.MSG_CONNECT_SUCCESS_TEST, new EventBusMessage(9, "服务器接口测试失败" + response.body(), "测试", 0));
                    }
                });
    }

    public static void TestInterface(String urlBase) {

        OkGo.<String>get(urlBase + "/Services/getGridModel")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            GoodsBean goodsBean = gson.fromJson(response.body(),
                                    new TypeToken<GoodsBean>() {
                                    }.getType());
                            if (goodsBean.getCode() == 200) {
                                LegoMessageManager.getInstance().sendMessage(Options.MSG_CONNECT_SUCCESS, new EventBusMessage(8, "服务器接口测试成功", "测试", 1));
                            }
                        } catch (Exception e) {
                            LegoMessageManager.getInstance().sendMessage(Options.MSG_CONNECT_SUCCESS, new EventBusMessage(8, "服务器测试接口返回异常", "测试", 0));
                        }


                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        LegoMessageManager.getInstance().sendMessage(Options.MSG_CONNECT_SUCCESS, new EventBusMessage(8, "服务器接口测试失败" + response.body(), "测试", 0));
                    }
                });
    }


    public static void getMessageProduct(boolean isNest, String urlBase) {

//        OkGo.<String>get(urlBase + "product.json")
        OkGo.<String>get(urlBase + "/Services/getGridModel")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            GoodsBean goodsBean = gson.fromJson(response.body(),
                                    new TypeToken<GoodsBean>() {
                                    }.getType());
                            if (goodsBean.getCode() == 200) {
                                final List<Goods> goodses = new ArrayList<Goods>();
                                goodses.clear();
                                if (goodsBean.getList().size() > 0) {
                                    for (final GoodsBean.ListBean goods : goodsBean.getList()) {
                                        final Goods goods1 = new Goods();
                                        goods1.setGridId(goods.getGridId());
                                        goods1.setGridCode(goods.getGridCode());
                                        goods1.setGridName(goods.getGridName());
                                        goods1.setMemo(goods.getMemo());
                                        goodses.add(goods1);
                                    }
                                    sExecutors.queryIO().execute(new Runnable() {
                                        @Override
                                        public void run() {
                                            try {
                                                AppDatabase.getInstance().getGoodsDao().save(goodses);
                                                LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(1, "获取产品数据成功", "产品", 1));
                                            } catch (Exception e) {
                                                LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(1, "产品插入数据库出错", "产品", 0));
                                                Log.d("error==", e.toString());
                                            }

                                        }
                                    });
                                }

                            } else {
                                LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(1, "产品获取数据出错" + goodsBean.getMessage(), "产品", 0));
                            }
                        } catch (Exception e) {
                            LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(1, "产品数据解析出错", "产品", 0));
                        }


                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(1, "产品访问服务器失败" + response.body(), "产品", 0));
                    }
                });
    }


    public static void getMessageDetail(boolean isNest, String urlBase) {

//        OkGo.<String>get(urlBase + "productDetail.json")
        OkGo.<String>get(urlBase + "/Services/getGridInfoModel")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            ProductDetailBean productDetailBean = gson.fromJson(response.body(),
                                    new TypeToken<ProductDetailBean>() {
                                    }.getType());

                            LogUtils.d("response.body()===="+response.body());
                            if (productDetailBean.getCode() == 200) {
                                final List<ProductDetail> ProductDetailList = new ArrayList<ProductDetail>();
                                ProductDetailList.clear();
                                if (productDetailBean.getList().size() > 0) {

                                }

                                for (final ProductDetailBean.ListBean productDetail : productDetailBean.getList()) {
                                    final ProductDetail productDetail1 = new ProductDetail();
//                                private String gridInfoId;
//                                private String gridType;
//                                private String partsWeight;
//                                private String standardWeight;
//                                private String standardTolerance;
//                                private String smallWeight;
//                                private String smallTolerance;
//                                private String memo;
                                    productDetail1.setGridId(productDetail.getGridId());

                                    productDetail1.setGridInfoId(productDetail.getGridInfoId());
                                    productDetail1.setGridType(productDetail.getGridType());
                                    productDetail1.setPartsWeight(productDetail.getPartsWeight());
                                    productDetail1.setStandardWeight(productDetail.getStandardWeight());
                                    productDetail1.setStandardTolerance(productDetail.getStandardTolerance());
                                    productDetail1.setSmallWeight(productDetail.getSmallWeight());
                                    productDetail1.setSmallTolerance(productDetail.getSmallTolerance());
                                    productDetail1.setMemo(productDetail.getMemo());

                                    ProductDetailList.add(productDetail1);
                                }
                                sExecutors.queryIO().execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            AppDatabase.getInstance().getProductDetailDao().save(ProductDetailList);
                                            LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(2, "产品详情获取成功", "产品详情", 1));
                                        } catch (Exception e) {
                                            LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(2, "产品详情插入数据库出错", "产品", 0));
                                            Log.d("error==", e.toString());
                                        }

                                    }
                                });

                            } else {
                                LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(2, "产品详情获取数据出错" + productDetailBean.getMessage(), "产品详情", 0));
                            }
                        } catch (Exception e) {
                            LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(2, "产品详情解析异常", "产品详情", 0));
//                            Toast.makeText(MainActivity.this, "解析异常" + e.toString(), Toast.LENGTH_SHORT).show();
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(2, "产品详情访问服务器失败" + response.body(), "产品详情", 0));

                    }
                });
    }


    public static void getMessageClass(boolean isNest, String urlBase) {
        OkGo.<String>get(urlBase + "/Services/getClassModel")
//        OkGo.<String>get(urlBase + "class.json")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            ClassesBean classesBean = gson.fromJson(response.body(),
                                    new TypeToken<ClassesBean>() {
                                    }.getType());
                            if (classesBean.getCode() == 200) {
                                final List<Classes> classesList = new ArrayList<Classes>();
                                classesList.clear();
                                if (classesBean.getList().size() > 0) {

                                    for (final ClassesBean.ListBean clessBean : classesBean.getList()) {
                                        final Classes classes = new Classes();
                                        classes.setClassId(clessBean.getClassId());
                                        classes.setClassName(clessBean.getClassName());
                                        classes.setMemo(clessBean.getMemo());
                                        classesList.add(classes);
                                    }
                                    sExecutors.queryIO().execute(new Runnable() {
                                        @Override
                                        public void run() {
                                            try {
                                                AppDatabase.getInstance().getClassesDao().save(classesList);
                                                LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(3, "班次获取数据成功", "班次", 1));
                                            } catch (Exception e) {
                                                LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(3, "班次插入数据库出错", "班次", 0));
                                                Log.d("error==", e.toString());
                                            }

                                        }
                                    });
                                }


                            } else {
                                LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(3, "班次获取数据出错" + classesBean.getMessage(), "班次", 0));
                            }
                        } catch (Exception e) {
                            LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(3, "班次数据解析出错", "班次", 0));

                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(3, "班次服务器出错", "班次", 0));
                    }
                });
    }

    public static void getMessageTeam(boolean isNest, String urlBase) {
        OkGo.<String>get(urlBase + "/Services/getWorkTeamModel")
//        OkGo.<String>get(urlBase + "team.json")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            TeamBean teamBean = gson.fromJson(response.body(),
                                    new TypeToken<TeamBean>() {
                                    }.getType());
                            if (teamBean.getCode() == 200) {
                                final List<Team> teamList = new ArrayList<Team>();
                                teamList.clear();
                                if (teamBean.getList().size() > 0) {

                                }

                                for (final TeamBean.ListBean teamBeanOne : teamBean.getList()) {
                                    final Team team = new Team();
                                    team.setTeamId(teamBeanOne.getTeamId());
                                    team.setTeamName(teamBeanOne.getTeamName());
                                    team.setMemo(teamBeanOne.getMemo());
                                    teamList.add(team);
                                }
                                sExecutors.queryIO().execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            AppDatabase.getInstance().getTeamDao().save(teamList);
                                            LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(4, "班组获取数据成功", "班组", 1));
                                        } catch (Exception e) {
                                            LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(4, "班组插入数据库出错", "班组", 0));
                                            Log.d("error==", e.toString());
                                        }

                                    }
                                });

                            } else {
                                LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(4, "班组获取数据出错" + teamBean.getMessage(), "班组", 0));

                            }
                        } catch (Exception e) {
                            LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(4, "班组插入数据库出错", "班组", 0));

                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(4, "班组服务器出错", "班组", 0));
                    }
                });
    }


    public static void getMessageStaff(boolean isNest, String urlBase) {
        OkGo.<String>get(urlBase + "/Services/getStaffModel")
//        OkGo.<String>get(urlBase + "staff.json")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            StaffBean staffBean = gson.fromJson(response.body(),
                                    new TypeToken<StaffBean>() {
                                    }.getType());
                            if (staffBean.getCode() == 200) {
                                final List<Staff> staffList = new ArrayList<Staff>();
                                staffList.clear();
                                if (staffBean.getList().size() > 0) {


                                    for (final StaffBean.ListBean teamListBean : staffBean.getList()) {
                                        final Staff staff = new Staff();
                                        staff.setStaffId(teamListBean.getStaffId());
                                        staff.setStaffName(teamListBean.getStaffName());
                                        staff.setMemo(teamListBean.getMemo());
                                        staffList.add(staff);
                                    }
                                    sExecutors.queryIO().execute(new Runnable() {
                                        @Override
                                        public void run() {
                                            try {
                                                AppDatabase.getInstance().getStaffDao().save(staffList);
                                                LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(5, "员工获取数据成功", "员工", 1));
                                            } catch (Exception e) {
                                                LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(5, "员工插入数据库出错", "员工", 0));

                                                Log.d("error==", e.toString());
                                            }

                                        }
                                    });

                                }


                            } else {
                                LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(5, "员工获取数据出错" + staffBean.getMessage(), "班次", 0));
                            }
                        } catch (Exception e) {
                            LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(5, "员工解析异常", "员工", 0));
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(5, "员工服务器出错", "员工", 0));
                    }
                });
    }


    public static void AllDelete() {
        sExecutors.queryIO().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    AppDatabase.getInstance().getGoodsDao().delete();
                    AppDatabase.getInstance().getProductDetailDao().delete();
                    AppDatabase.getInstance().getClassesDao().delete();
                    AppDatabase.getInstance().getTeamDao().delete();
                    AppDatabase.getInstance().getStaffDao().delete();
                } catch (Exception e) {
                    Log.d("error==", e.toString());
                }
            }
        });


    }


    public static void getMessagePost(Context context, List<Post> postList, String deviceCodeStr, boolean isUpdate) {

        String baseUrl = PreferenceManager.getDefaultSharedPreferences(context).getString("scales_post_url_post", "http://yzqa2q2g.ipyingshe.net");

        PostMessage postMessage = new PostMessage();

        List<PostProduct> postProductList = new ArrayList<>();
        postProductList.clear();

        for (Post post : postList) {
            PostProduct postProduct = new PostProduct();
            ClonePostUtil.ClonePost(post, postProduct);
            postProductList.add(postProduct);
        }

        postMessage.setDeviceCode(deviceCodeStr);
        postMessage.setTime(formatter.format(System.currentTimeMillis()));
        postMessage.setList(postProductList);

        String postStr = gson.toJson(postMessage);

        LogUtils.d("json=====" + postStr);

//        OkGo.<String>post("http://yzqa2q2g.ipyingshe.net/Services/uploadWeightInfo")
        OkGo.<String>post(baseUrl + "/Services/uploadWeightInfo")
                .upJson(postStr)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            PostRebackMess postRebackMess = gson.fromJson(response.body(),
                                    new TypeToken<PostRebackMess>() {
                                    }.getType());
                            if (postRebackMess.getCode() == 200) {

                                sExecutors.queryIO().execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            for (Post post : postList) {
                                                post.setPostSuccess(1);
                                            }
                                            if (isUpdate) {
                                                for (Post postUpdate : postList) {
                                                    AppDatabase.getInstance().getPostDao().update(postUpdate);
                                                }

                                            } else {
                                                AppDatabase.getInstance().getPostDao().save(postList);
                                            }

                                            LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(6, "数据提交成功", "称重数据提交", 1));
                                        } catch (Exception e) {
                                            LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(6, "数据提交成功但插入数据库出错", "称重数据提交", 0));

                                            Log.d("error==", e.toString());
                                        }

                                    }
                                });


                            } else {

                                sExecutors.queryIO().execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            if(!isUpdate){
                                                AppDatabase.getInstance().getPostDao().save(postList);
                                            }
                                            LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(6, postRebackMess.getMessage(), "称重数据提交", 0));
                                        } catch (Exception e) {
                                            LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(6, "数据提交失败并且插入数据库出错", "称重数据提交", 0));
//                                            Log.d("error==", e.toString());
                                        }

                                    }
                                });
                            }
                        } catch (Exception e) {
                            sExecutors.queryIO().execute(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        if(!isUpdate){
                                            AppDatabase.getInstance().getPostDao().save(postList);
                                        }
                                        LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(6, "数据提交失败", "称重数据提交", 0));
                                    } catch (Exception e) {
                                        LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(6, "数据提交失败并且插入数据库出错", "称重数据提交", 0));
//                                        Log.d("error==", e.toString());
                                    }

                                }
                            });
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        sExecutors.queryIO().execute(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    if(!isUpdate){
                                        AppDatabase.getInstance().getPostDao().save(postList);
                                    }
                                    LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(6, "数据提交服务器出错", "称重数据提交", 0));
                                } catch (Exception e) {
                                    LegoMessageManager.getInstance().sendMessage(Options.MSG_POST_SUCCESS, new EventBusMessage(6, "服务器出错并且插入数据库出错", "称重数据提交", 0));
//                                    Log.d("error==", e.toString());
                                }

                            }
                        });
                    }
                });

    }


    public static long convert2long(String date) {
        try {
            if (!TextUtils.isEmpty(date)) {
                SimpleDateFormat sf = new SimpleDateFormat(TIME_FORMAT);
                return sf.parse(date).getTime();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0l;
    }

}